# All Rights Reserved
#Copyright Bakhtiar AHamid <kedai@kedai.com.my>
#
# Sept 2001 "Mark W. Alexander" <slash@dotnetslash.net> (proxy suport)
# Nov 2001 Gregory Dudek (better start/end pattern handling)
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions
#are met:
#1. Redistributions of source code must retain the above copyright
#notice, this list of conditions and the following disclaimer.
#2. Redistributions in binary form must reproduce the above copyright
#notice, this list of conditions and the following disclaimer in the
#documentation and/or other materials provided with the distribution.
#3. The name of the author may not be used to endorse or promote products
#derived from this software without specific prior written permission
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE. CHANGES AND CUSTOMIZATION MUST RETAIN THIS HEADER.
#
# Author: Bakhtiar AHamid <kedai@kedai.com.my>

##############################################################################
from Acquisition import Implicit
from Globals import Persistent
from AccessControl.Role import RoleManager
from AccessControl import ClassSecurityInfo
from AccessControl import getSecurityManager

from Globals import InitializeClass
from Globals import DTMLFile, HTMLFile
from Globals import MessageDialog
from OFS.Image import Image
from DocumentTemplate.DT_Util import html_quote
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from Products.BTreeFolder2.BTreeFolder2 import BTreeFolder2
from Products.ZCTextIndex import ZCTextIndex  #to add lexicon
from ZPublisher.HTTPRequest import record #magic for zctextindex
from Products.ZCatalog import ZCatalog
import zBookmark
import traceback, sys, os
#from OFS.Folder import Folder

addOBForm = PageTemplateFile('zpt/addOBForm.zpt',globals())

def manage_addOBookmark(self, id, title='', REQUEST=None):
    """the add method"""
    ob = OBookmark(id, title)
    self._setObject(id,ob)
    ob = self._getOb(id)
    ob._postinit(REQUEST)
    if REQUEST is not None:
        return self.manage_main(self, REQUEST, update_menu=1)
    #if REQUEST is not None:
    #    return REQUEST.RESPONSE.redirect('manage_workspace')

class OBookmark(BTreeFolder2, Implicit, Persistent, RoleManager):
    """The Folder Product."""

    meta_type = 'Bookmark Folder'

    manage_options=BTreeFolder2.manage_options + (
              {'label' : 'Edit', 'action' : 'editOBookmarkForm', 'help': ('OBookmark','edit.txt')},
            )

    security=ClassSecurityInfo()
    security.declareProtected('View management screens','editOBookmarkForm')
    editOBookmarkForm = PageTemplateFile('zpt/editOBookmarkForm',globals())
    defstyle_css = DTMLFile('zpt/style_css',globals())
    defjquery = DTMLFile('zpt/jquery.js',globals())
    defjquerytag = DTMLFile('zpt/jquery.tagto.js',globals())
    defmytag = DTMLFile('zpt/mytag.js',globals())
    #defmyindex = PageTemplateFile('zpt/index_html',globals())
    master = PageTemplateFile('zpt/master',globals())
    taglist = PageTemplateFile('zpt/taglist',globals())
    img1 = DTMLFile('zpt/images/anibanner01.jpg', globals())
    img2 = DTMLFile('zpt/images/bg01.jpg', globals())
    index_html = PageTemplateFile('zpt/index_html',globals())
    sres= PageTemplateFile('zpt/sres',globals())
    security.declarePublic('addForm')
    addForm = zBookmark.addForm
    security.declarePublic('editBookmarkForm')
    editBookmarkForm = zBookmark.zBookmark.editBookmarkForm
    security.declareProtected('Add Bookmarks','manage_addzBookmark')
    manage_addzBookmark = zBookmark.manage_addzBookmark
    security.declareProtected('Edit Bookmarks','manage_editzBookmark')
    manage_editzBookmark = zBookmark.zBookmark.manage_editzBookmark

    def __init__(self, id, title=''):
        """my init"""
        self.id = id
        self.title = title
        try: # Be flexible with the BTreeFolder2 implementation , stolen from kaivo's doclib
                BTreeFolder2.__init__(self)
        except:
                BTreeFolder2.__init__(self, id)

    def _postinit(self, REQUEST):
        """adding default stuff after the fact"""
        r = REQUEST
        #r.set('file', self.defmyindex)
        #print self.defindex_html.read()
        self.manage_addDTMLMethod('style.css',file=self.defstyle_css)
        self.manage_addDTMLMethod('jquery.js',file=self.defjquery)
        self.manage_addDTMLMethod('jquery.tagto.js',file=self.defjquerytag)
        self.manage_addDTMLMethod('mytag.js',file=self.defmytag)
        #self.manage_addProduct['PageTemplates'].manage_addPageTemplate('index_html', REQUEST=r)
        self.manage_addFolder('images')
        myfol = getattr(self, 'images')
        #print os.getcwd()
        myfol.manage_addImage('bg01.jpg',file=open('Products/tandabuku/zpt/images/bg01.jpg'))
        myfol.manage_addImage('anibanner01.jpg',file=open('Products/tandabuku/zpt/images/anibanner01.jpg'))
        RESPONSE = REQUEST.RESPONSE
        #create our Catalog
        ZCatalog.manage_addZCatalog(self,id='Catalog',
                title='',vocab_id='create_default_catalog_',REQUEST=None)
        zc = getattr(self,'Catalog')
        elements=[{'group':'Word Spliter'}]
        ZCTextIndex.manage_addLexicon(zc, 'reslex','', elements)
        #set extra stuff to add ZCTextIndex.  extra is a record() and we set attributes accordingly
        #should be done only once, and used when we want to add ZCTextIndex
        extra=record()
        setattr(extra,'lexicon_id','reslex')
        setattr(extra,'index_type','Cosine Measure') 
        zc.manage_addColumn('title')
        zc.manage_addColumn('url')
        zc.manage_addColumn('meta_type')
        zc.manage_addColumn('tags')
        zc.manage_addColumn('desc')
        zc.manage_addColumn('uid')
        zc.manage_addColumn('id')
        zc.manage_addColumn('status')
        zc.manage_addIndex('desc','ZCTextIndex',extra)
        zc.manage_addIndex('tags','KeywordIndex')
        zc.manage_addIndex('uid','FieldIndex')
        zc.manage_addIndex('status','FieldIndex')
        zc.manage_addIndex('dateposted','DateIndex')

    def getLatest(self):
        """get the latest 10 marks added"""
        zc = getattr(self, 'Catalog')
        res = zc(sort_order="reverse",sort_on="dateposted", sort_limit=10)
        return res

    def getUserTagList(self):
        """get the latest 10 marks added"""
        uid = getSecurityManager().getUser().getId()
        zc = getattr(self, 'Catalog')
        res = zc(uid=uid, sort_order="reverse",sort_on="dateposted")
        #print res
        return res

    def getSearchResults(self, term):
        """retrun matched results"""
        zc = getattr(self, 'Catalog')
        res = zc(desc = term, status='public', sort_order="reverse",sort_on="dateposted")
        return res

    def getTags(self, q):
        """return avialable tags"""
        cat = self.Catalog
        res = cat.uniqueValuesFor('tags')
        unik = ""
        if len(q.strip().split()) > 1:
            q = q.strip().split()[-1]

        if len(q) > 2:
            for x in res:
                if q.lower() in x.lower():
                    unik += ' <a href="#">%s</a> ' % x 
            return unik

    def gotRoot(self):
        """return our root url"""
        return self.absolute_url()

    def getRoot(self):
        """return our root url"""
        return self

    #def __before_publishing_traverse__(self, unused, REQUEST):
    #   """Save the rest of the path as 'traverse_subpath'."""
    #   request = REQUEST
    #   request.set('traverse_subpath',
    #               reversed(request['TraversalRequestNameStack']))
       # Tell the publisher to stop traversing now.
    #   request['TraversalRequestNameStack'][:] = []


    def tag_all_html(self):
        """present all the tags"""
        text = ""
        tg = self.tagsAndPixels().items()
        tg.sort()
        for k,v in tg:
            text +=  '<a href="taglist?tagid=%s"  style="font-size:%sem;" class="PopularTag">%s</a> ' % (k, v, k)
        return text

    def tag(self, tagid):
        """presentation of tag """
        #print tagid
        res = self.Catalog.searchResults(tags=tagid, sort_on='dateposted', meta_type='Bookmark',
                                   sort_order='reverse')
        return res

    def tagsAndPixels(self):
        """ returns a dictionary with (tag, pixelSize) pairs
            based on number of posts cataloged with the tags """
        zc = getattr(self, 'Catalog')
        tags = [tag for tag in zc.uniqueValuesFor('tags') if tag.strip()]
        tags.sort()
        zenbat = {}
        for tag in tags:
            tagkop = zc.searchResults(tags=tag, 
                        meta_type='Bookmark')
            zenbat[tag] = len(tagkop)

        maxpx = 1.60
        minpx = 0.60
        difpx = maxpx-minpx

        if zenbat.values():
            maxnum = max(zenbat.values())
            minnum = max(zenbat.values())
        else:
            maxnum = 0
            minnum = 0


        hiz = {}
        for k,v in zenbat.items():
            hiz[k] = float(difpx*v/maxnum)+minpx
        
        return hiz

    def userDelete(self, id, REQUEST=None):
        """user delete bookmark"""
        uid = getSecurityManager().getUser().getId()
        bookitem = getattr(self, str(id), None)
        if bookitem is not None and bookitem.uid == uid:
            self.manage_delObjects(str(id))
        if REQUEST is not None:
            #REQUEST.response.redirect(self.gotRoot())
            REQUEST.response.redirect(REQUEST['HTTP_REFERER'])

    def all_meta_types(self):
        """ What types can you add to this objectManager? """
        allowedMetaTypes = ('ZCatalog', 'DTML Method', 'DTML Document', 'Script (Python)',
                             'ex User Folder','Page Template', 'Z Search Interface', 'Cookie Crumbler',
				'Cookie Crumbler (Standalone)')
        result = []
        import Products
        for metaType in Products.meta_types:
            if metaType['name'] in allowedMetaTypes:
                result.append(metaType)
        #my_meta_types = {'name':'Xdox','action':'manage_addXdoxForm'}
        my_meta_types = {'name':'Bookmark','action':'addForm'}
        result.append(my_meta_types)
                #print result
        return result

InitializeClass(OBookmark)
